package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;

import android.R.integer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.tencent.mm.opensdk.utils.Log;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.adapter.CommonAdapter;
import com.ycsj.goldmedalnewconcept.adapter.ViewHolder;
import com.ycsj.goldmedalnewconcept.bean.VersionInfo;
import com.ycsj.goldmedalnewconcept.bean.ClassInformationResponse.classinfo;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.view.PullToRefreshLayout;

//新版本介绍
@SuppressLint("NewApi")
public class NewVersionActivity extends Activity implements OnClickListener,
		SwipeRefreshLayout.OnRefreshListener {

	// 正常请求
	public static final int NORMAL = 0X110;

	// 下拉刷新
	public static final int PULLTOREFRESH = 0X120;

	// 返回
	private LinearLayout llBack;

	// 加载视图
	private LinearLayout llLoading;

	// 空数据
	private LinearLayout llEmpty;

	// 下拉刷新控件
	private PullToRefreshLayout ptrl;

	private ImageView iv_back;
	private ListView lv_newversion;
	private ArrayList<String> list;
	private View ll_logo;
	private List<VersionInfo> oldDatas;

	private LvAdapter adapter;

	//头布局的版本号
	private TextView tvVersion;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_newversion);

		// 设置状态栏颜色
		setBar();

		list = new ArrayList<String>();
		list.add("1");
		initView();

		setOnListener();

		initData();

		http(NORMAL);
	}

	/**
	 * 初始化View的方法
	 */
	private void initView() {
		iv_back = (ImageView) findViewById(R.id.iv_back);
		lv_newversion = (ListView) findViewById(R.id.lv_newversion);

		// 头布局
		ll_logo = LayoutInflater.from(getBaseContext()).inflate(
				R.layout.head_newversion, null);
		tvVersion = (TextView) ll_logo.findViewById(R.id.tv_head_version);
		
		

		llLoading = (LinearLayout) findViewById(R.id.ll_loading);
		llEmpty = (LinearLayout) findViewById(R.id.ll_empty);
		ptrl = (PullToRefreshLayout) findViewById(R.id.refresh_view);
	}

	/**
	 * 请求服务器数据
	 */
	private void http(final int method) {

		OkHttpClient mOkHttpClient = new OkHttpClient();
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("apptype", "Android");
		builder.add("page", "0");
		Request request = new Request.Builder()
				.url("http://m.moregolden.com/ycsj_platform/AppVerMsg")
				.post(builder.build()).build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onResponse(Response arg0) throws IOException {
				String json = arg0.body().string();

				try {
					if (!TextUtils.isEmpty(json)) {
						// 解析Json
						JSONObject object = new JSONObject(json);
						if ("1".equals(object.getString("state"))) {
							// 获取返回的array数组
							JSONArray array = object.getJSONArray("list");
							final List<VersionInfo> newDatas = new ArrayList<>();
							for (int i = 0; i < array.length(); i++) {
								JSONArray res = (JSONArray) array.get(i);
								VersionInfo info = new VersionInfo();
								info.setName(res.getString(1));
								info.setContent(res.getString(4));
								info.setVersion(res.getString(3));
								newDatas.add(info);
							}

							// 更新UI
							runOnUiThread(new Runnable() {
								public void run() {

									if (method == NORMAL) {
										// 正常请求
										if (llLoading != null) {
											llLoading.setVisibility(View.GONE);
										}
										oldDatas.addAll(newDatas);
										lv_newversion.setAdapter(adapter);
										tvVersion.setText("金牌君"+oldDatas.get(0).getVersion());
									} else {
										// 下拉刷新
										oldDatas.clear();
										oldDatas.addAll(newDatas);
										ptrl.refreshFinish(PullToRefreshLayout.REFRESH_SUCCEED);
										tvVersion.setText("金牌君"+oldDatas.get(0).getVersion());
										adapter.notifyDataSetChanged();
									}
								}
							});

						} else {
							// 证明没有数据
							runOnUiThread(new Runnable() {
								public void run() {

									// 正常请求
									if (llLoading != null) {
										llLoading.setVisibility(View.GONE);
									}
									Toast.makeText(NewVersionActivity.this,
											"网络错误", Toast.LENGTH_SHORT).show();
								}
							});
						}

					}

				} catch (Exception e) {
					// 打印错误信息
					Log.i("test", e.toString());
				}
			}

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					public void run() {
						// 隐藏加载框
						// 正常请求
						if (llLoading != null) {
							llLoading.setVisibility(View.GONE);
						}
						Toast.makeText(NewVersionActivity.this, "网络错误",
								Toast.LENGTH_SHORT).show();
					}
				});
			}
		});

	}

	/**
	 * 初始化适配器的方法
	 */
	private void initData() {
		oldDatas = new ArrayList<>();
		adapter = new LvAdapter(this, oldDatas, R.layout.list_newversion);
		// 添加头布局
		lv_newversion.addHeaderView(ll_logo);
	}

	/**
	 * 设置监听的方法
	 */
	private void setOnListener() {
		iv_back.setOnClickListener(this);

		ptrl.setOnRefreshListener(this);
	}

	/**
	 * 点击事件
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_back:
			// 返回
			finish();
			break;
		}
	}

	/**
	 * ListView的适配器
	 */
	class LvAdapter extends CommonAdapter<VersionInfo> {

		public LvAdapter(Context context, List<VersionInfo> datas, int layoutId) {
			super(context, datas, layoutId);
		}

		@Override
		public void convert(ViewHolder holder, VersionInfo info) {
			// 标题
			TextView tvName = holder.getView(R.id.tv_name);
			tvName.setText(info.getName());

			// 更新内容
			TextView tvContent = holder.getView(R.id.tv_content);
			tvContent.setText(info.getContent());

			// 更新版本号
			TextView tvVersion = holder.getView(R.id.tv_version);
			tvVersion.setText("最新版本号:" + info.getVersion());

			// 线条
			View line = holder.getView(R.id.view);

		}

	}

	/**
	 * 设置沉浸状态栏的方法,需要在setContentView()之后调用
	 */
	private void setBar() {
		// 兼容5.0+，状态栏设置透明
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			Window window = getWindow();
			window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			window.getDecorView().setSystemUiVisibility(
					View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
							| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
			window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
			window.setStatusBarColor(Color.TRANSPARENT);
		} else
		// 为了沉浸式状态栏 4.4以上才有
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		}
	}

	/**
	 * 下拉刷新
	 */
	@Override
	public void onRefresh() {
		http(PULLTOREFRESH);
	}
}
